import React, { Component, PropTypes } from 'react';
import { Utility, GxSearchBar, RelationItem, ApiInfo, Refresh } from 'components';
import { connect } from 'react-redux';
import * as CommonActions from 'redux/modules/reduxCommon';
const styles = require('./scss/TaskRelated.scss');

@connect(
  state => ({
    Title: state.Common.Title,                                          // 标题
    UrlParams: state.Common.UrlParams,                                  // URL参数
    TaskRelatedList: state.Common.TaskRelatedList,                      // 任务关联列表
  }),
  { ...CommonActions })

export default class TaskRelated extends Component {
  static propTypes = {
    Title: PropTypes.string,                                            // 标题
    UrlParams: PropTypes.object,                                        // url 参数
    TaskRelatedList: PropTypes.object,                                  // 任务关联列表
    onDeleteByFields: PropTypes.func,                                   // 
    onSetContent: PropTypes.func,                                       // 
    onUpdateRedux: PropTypes.func,                                      // 
    onApiGet: PropTypes.func,                                           // 
    onApiPost: PropTypes.func,                                          // 
    onApiPut: PropTypes.func,                                           // 
  };

  constructor(props) {
    super(props);
    this.state = { RefreshComplete: true, NextDataComplete: true, };
    const _RelationTaskList = [
      {
        content: '天有牛郞织女，地上金童玉女，唯吾与尔。', scope: 'MYSELF', pId: 7218,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '七夕如愿盼今朝，红叶香残怨可消。朝朝暮暮图永久，缠缠绵绵诉心焦。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }]
      },
      {
        content: '亲亲你我， 私守楼阁，鹊桥之夜永定今生!', scope: 'ALL', pId: 361827,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河之上，一世的等待', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
      {
        content: '银河陷落，爱意沸腾，总不比乞巧合欢。', scope: 'MYSELF', pId: 0,
        extTaskUser: [{ taskUserName: 'wangpeng' }, { taskUserName: '李卫东' }, { taskUserName: '廖海兵' }]
      },
    ];
    this.state.RelationTaskList = _RelationTaskList;
  }

  componentDidMount() {
    this.state.IsMount = true;
    // const { TaskRelatedList } = this.props;
    // const { List } = TaskRelatedList || {};
    // if (!Utility.isArray(List)) {
    //   this.__InitData({});
    // }
  }

  componentWillUnmount() {
    delete this.state.IsMount;
  }

  /**
   * 更新渲染
   */
  __UpdateRender() {
    if (!!this.state.IsMount) {
      this.setState({ __CurrentTempDate: new Date().getTime() });
    }
  }

  __InitData(condition) {
    const keyword = this.state.KeyWord;
    const params = Object.assign({}, { keyword, page: 0, size: 15 }, condition || {});
    const { onApiGet } = this.props;
    if (!Utility.isFunction(onApiGet)) {
      return;
    }

    const __Complete = () => {
      delete this.state.IsBusying;
      this.state.NextDataComplete = true;
      this.state.RefreshComplete = true;
      this.__UpdateRender();
    };
    const __self = this;
    onApiGet('TaskRelatedList', ApiInfo.JXDB.BackupList, { params: params }).then(() => {
      __self.__InitDataByResult();
      __Complete();
    }, () => {
      __Complete();
    });
  }

  __InitDataByResult() {
    const { TaskRelatedList } = this.props;
    const { Condition } = TaskRelatedList || {};
    const { IsExistsNextData } = Condition || {};
    this.state.IsNextData = IsExistsNextData;
  }

  /**
  * 搜索事件
  * 
  * @param {any} key 
  * @returns 
  * @memberof GmessageDealt
  */
  __HandlerSearch(key) {
    this.state.__TempKeyWork = key;
    if (!!this.state.isLockSearch) {
      return;
    }
    this.state.isLockSearch = true;
    this.state.QTime = new Date().getTime();

    const _inter = setInterval(() => {
      const __CTime = new Date().getTime();
      const _OTime = this.state.QTime;
      this.state.TempIndex++;
      console.log('index -->:', this.state.TempIndex, '--> key:', this.state.__TempKeyWork);
      if (this.state.KeyWord === this.state.__TempKeyWork) {
        this.state.TempIndex = 0;
        console.log('KeyWord === key--index -->:', this.state.TempIndex);
        clearInterval(_inter);
        this.state.isLockSearch = false;
      }

      if (__CTime - _OTime > 1000) {
        if (!!this.state.IsBusying) {
          console.log('正在调用接口请等待....');
          return;
        }
        this.state.IsBusying = true;

        clearInterval(_inter);
        this.state.KeyWord = this.state.__TempKeyWork;
        delete this.state.__TempKeyWork;
        this.state.isLockSearch = false;
        console.log('开始调用接口了index -->:%d,KeyWord:%s', this.state.TempIndex, this.state.KeyWord);
        this.__InitData({}, false);
      }
    }, 200);
  }

  __HandlerOnKeep() {
    const { onApiPut, onUpdateRedux, onSetContent } = this.props;
    if (!Utility.isFunction(onApiPut)) {
      return;
    }

    const self = this;
    const __Submit = () => {
      Utility.$loading();
      onApiPut('GMessageDetailInfo', ApiInfo.JXDB.ToBackup, {}).then(() => {
        onSetContent('GxMessageDealt', null);
        onUpdateRedux();
        self.__UpdateRender();
        Utility.$actionSheet('存档成功');
        Utility.$loadingHide();
      }, () => {
        Utility.$loadingHide();
      });
    };
    Utility.$showDialogConfirm('您真的存档吗？', null, () => {
      __Submit();
    });
  }

  __HandlerNextData() {
    const { TaskRelatedList } = this.props;
    const { Condition } = TaskRelatedList || {};
    const { IsExistsNextData } = Condition || {};
    if (!IsExistsNextData) {
      return;
    }
    this.state.NextDataComplete = false;
    this.__UpdateRender();
    this.__InitData(Condition, true);
  }

  __HandlerRefresh() {
    this.state.RefreshComplete = false;
    this.__UpdateRender();
    this.__InitData({}, false);
  }

  __BuildHTML() {
    // const { TaskRelatedList } = this.props;
    // const { List } = TaskRelatedList || {};
    // if (!Utility.isArray(List)) {
    //   return null;
    // }
    const { RelationTaskList } = this.state;
    if (!Utility.isArray(RelationTaskList)) {
      return null;
    }
    return RelationTaskList.map((item, index) => {
      const { content, extTaskUser, scope, pId } = item || {};
      const _relationInfo = {};
      _relationInfo.content = content || '';
      _relationInfo.extTaskUser = extTaskUser || [];
      _relationInfo.scope = scope || '';
      _relationInfo.pId = pId;
      return (
        <div className={styles.relatedContainer + ' ' + (index === RelationTaskList.length - 1 ? styles.lastCss : '')} key={'related_list_' + index}>
          <RelationItem RelationInfo={_relationInfo} />
        </div>
      );
    });
  }

  render() {
    const { RefreshComplete, NextDataComplete, IsNextData } = this.state;

    return (
      <div className={styles.taskRelatedCss}>
        <div className={styles.search}>
          <GxSearchBar Title="标签、任务、接受者"
            onSearch={this.__HandlerSearch.bind(this)}
          />
        </div>
        <Refresh Percentage={20} RefreshComplete={RefreshComplete} NextDataComplete={NextDataComplete}
          onRefresh={this.__HandlerRefresh.bind(this)} onNextData={this.__HandlerNextData.bind(this)}>
          <div className={styles.list}>
            {
              this.__BuildHTML()
            }
          </div>
        </Refresh>
        <div className={styles.last}>
          {
            IsNextData === false &&
            <span> 别扯了,我是有底线的。</span>
          }
        </div>
      </div>
    );
  }
}
